<script setup lang="ts">
import { addStaff } from '@/api';
import Wrap from '@/components/form-item-wrap/index.vue';
import { defaultWorkerForm, labelAlign, labelCol } from '@/const';
import type { AddStaffParam } from '@/types';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { reactive, ref, watchEffect } from 'vue';
import { useRouter } from 'vue-router';
import BaseForm from './base-form.vue'
import BodyForm from './boarding.vue'

const router = useRouter();
const formRef = ref();

const formState = reactive<AddStaffParam>(structuredClone(defaultWorkerForm));

const onAdd = () => {
	addStaff(Object.assign(formState, {
		contactPhone: Number(formState.contactPhone)
	})).then(res => {
		if (res.Code === 200) {
			message.success('操作成功');
			router.push('/personnel/worker');
		}
	});
};

const submit = () => {
	formRef.value.validate().then(() => {
		onAdd();
	})
}

watchEffect(() => {
	if (formState.birthday) {
		const birthYear = dayjs(formState.birthday).year();
		const currentYear = dayjs().year();
		if (birthYear && birthYear < currentYear) {
			formState.age = currentYear - birthYear;
		}
	}
});


const formRules = {
	name: [
		{
			required: true,
			message: '请输入名称',
		},
	],
	phone: [
		{
			required: true,
			message: '请输入联系电话',
		},
	],
	birthday: [
		{
			required: true,
			message: '请选择出生年月',
		},
	],
	startTime: [
		{
			required: true,
			message: '请选择入职时间',
		},
	],
};

</script>

<template>
	<div class="form-wrap person-add-form">
		<a-form ref="formRef" :rules="formRules" :model="formState" class="base-form" :label-col="labelCol" :label-align="labelAlign">
			<Wrap title="基础信息">
				<BaseForm :formState></BaseForm>
			</Wrap>
			<Wrap title="入职信息">
				<BodyForm :formState></BodyForm>
			</Wrap>
		</a-form>
		<div class="text-center">
			<a-button type="primary" @click="submit" class="mr20">
				完成入职
			</a-button>
			<RouterLink to="/personnel/worker">
				<a-button>取消</a-button>
			</RouterLink>
		</div>
	</div>
</template>
<style scoped lang="less">
.person-add-form {
	:deep(.base-form) {
		.ant-form-item {
			margin-inline-end: 0;
			margin-bottom: 20px;
		}
	}
}
</style>
